package jcommon.chap9_templating.velocity.defineengin;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

import jcommon.chap9_templating.velocity.demoframework.VelocityDemo;
import jcommon.chap9_templating.velocity.macro.bean.Appointment;
import jcommon.chap9_templating.velocity.macro.bean.Location;
import jcommon.chap9_templating.velocity.macro.bean.Organization;
import jcommon.chap9_templating.velocity.macro.bean.Volunteer;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class DefineEngineByFileDemo extends VelocityDemo {

	@Override
	protected void processWriterByVolicity(StringWriter writer)
			throws Exception {
		getVelocityEngine().mergeTemplate(
				"jcommon/chap9_templating/velocity/defineengin/results.vm",
				getVelocityContext(), writer);
	}

	protected VelocityEngine getVelocityEngine() {
		// Create and initialize a VelocityEngine setting a configuration
		// property
		VelocityEngine vEngine = new VelocityEngine();
		try {
			vEngine.init(getClass().getResource("velocity.properties")
					.getFile());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return vEngine;
	}

	@Override
	public Reader getTemplateReader() {
		// Get a stream to read in our velocity template. The
		// organize.vm file is loaded from the classpath and is stored
		// in the same package as the current class.
		InputStream templateStream = getClass().getResourceAsStream("test.vm");
		Reader reader = new InputStreamReader(templateStream);
		return reader;
	}

	@Override
	protected VelocityContext getVelocityContext() {
		VelocityContext context = new VelocityContext();
		context.put("appointment", getTestAppointment());
		return context;
	}

	private Appointment getTestAppointment() {
		Appointment a = new Appointment();
		Location l = new Location();
		Organization o = new Organization();
		Volunteer v = new Volunteer();
		a.setLocation(l);
		a.setOrganization(o);
		a.setVolunteer(v);

		v.setFirstName("John");
		v.setLastName("S.");
		a.setStartTime("09:00 AM");
		a.setEndTime("02:00 PM");
		a.setDate("Monday");
		l.setName("Boston Homeless Veterans Shelter");

		return a;
	}
}
